﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using YGOP.ESB.Log.Model;
using YGOP.ESB.Log;
using System.Web.SessionState;
using GU.WebERP.Core.AjaxFx;

namespace GU.WebERPApp.Handlers
{
    /// <summary>
    /// AjaxFxHttpHandler 的摘要说明
    /// </summary>
    public class AjaxFxHttpHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                // 查找调用的方法
                AjaxFxMethodInfo method = AjaxFxClassManager.FindMethod(context);
                if (method == null)
                {
                    return;
                }

                // 写用户日志
                if (method.Log)
                {
                    //User user = context.Session["User"] as User;
                    var log = new EsbUserLog();
                    log.Behavior = method.Code.ToLower();
                    //log.UserId = user == null ? null : user.Id;
                    //log.UserName = user == null ? null : user.Name;
                    log.UserIP = context.Request.UserHostAddress;
                    log.PageUrl = context.Request.Url.AbsoluteUri;
                    log.UrlReferrer = context.Request.UrlReferrer == null ? null : context.Request.UrlReferrer.ToString();
                    log.Tags = method.Code.ToLower();
                    log.TagsEx = method.Description;
                    LogManager.WriteEsbUserLog(log);
                }

                // 判断方法是否需要 Session 验证
                if (method.MustSession)
                {
                    //if (user == null || string.IsNullOrEmpty(user.Name))
                    //{
                    //    context.Response.Write("Session 过期或未登录");
                    //    return;
                    //}
                }

                // 调用方法
                var s = AjaxFxClassManager.CallMethod(context, method);
                if (s != null)
                {
                    context.Response.Write(s.ToJson());
                }
            }
            catch (Exception ex)
            {
                YGOP.ESB.Log.LogManager.WriteAppError(ex);
                throw ex;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}